var Const = require('../connect/connect');
var express = require('express');
var app = express();
const multer = require('multer')
const fs = require('fs')
const path = require('path')
var pool = Const.pool //数据库连接池
const Redis = require('ioredis');
const redis = new Redis({
    host: 'localhost', // Redis服务器的主机地址
    port: 6379, // Redis服务器的端口号
    db: 1 //（可选）选择指定的数据库，默认连接到"0"号数据库
});

var jwt = require("jsonwebtoken")
//撒盐，加密时候混淆
var secret = '123bingjspoiuytrewqlkjhgfdsa'
//生成token
//info也就是payload是需要存入token的信息
function createToken(info) {
    let token = jwt.sign(info, secret, {
        //Token有效时间 单位s
        expiresIn:60 * 60*60*24 * 7
    })
    return token
}

//验证Token
function verifyToken(token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, secret, (error, result) => {
            if(error){
                reject(error)
            } else {
                resolve(result)
            }
      })
    })
}
redis.on('error', err => {
    if (err) {
      console.log('Redis链接错误');
      console.log(err);
      redis.quit() // 链接失败退出链接
    }
  })
  
  redis.on('ready', () => {
    console.log('Redis链接成功');
  })
  
var Model = function () {
    this.LoginResult = null;//登录结果
    this.Headimg = null;
    this.idnum = 0;//
    this.QQ = 0;
    this.TEL = 0
    var _this = this;
    this.setVideos = function(callback){
        // 读取本地文件夹
        const folderPath = 'E:/videos';
        var new_arr = [];
        function readFilesInFolders() {
            return new Promise((resolve, reject) => {
                fs.readdir(folderPath, (err, files) => {
                    console.log(files,'111')
                    if (err) {
                        console.error('Error reading folder:', err);
                        reject(err);
                    }
                    
                    const promises = files.map(folderName => {
                        const folderFullPath = path.join(folderPath, folderName);
                        return new Promise((resolve, reject) => {
                            fs.readdir(folderFullPath, (err, subFiles) => {
                                if (err) {
                                    console.error('Error reading subfolder1:', err);
                                    reject(err);
                                }
                                const imgFiles = subFiles.filter(file => file.endsWith('.jpg') || file.endsWith('.png'));
                                const videoFiles = subFiles.filter(file => file.endsWith('.mp4') || file.endsWith('.mkv'));
        
                                const folderObject = {
                                    name: folderName,
                                    img: path.join(folderFullPath, imgFiles[0]).split('E:')[1].replace('videos','imgshow'),
                                    videos: videoFiles
                                };
                                resolve(folderObject);
                            });
                        });
                    });
         
                    Promise.all(promises)
                        .then(results => {
                            new_arr = results;
                            resolve(new_arr);
                        })
                        .catch(err => {
                            reject(err);
                        });
                }); 
            });
        }
        
        readFilesInFolders()
            .then(result => {
                pool.getConnection(function(err,connection){
                    new_arr.forEach(video => {
                        connection.query('TRUNCATE TABLE video',(err1,result)=>{ 
                            connection.query('TRUNCATE TABLE video_item',(err2,result)=>{
                                connection.query('INSERT INTO video (name, img) VALUES (?, ?) ON DUPLICATE KEY UPDATE name = name', [video.name, video.img], (error, results, fields) => {
                                    if (error) {
                                        console.error(error);
                                    } else {
                                        const videoId = results.insertId;
                                        video.videos.forEach((videoFile, index) => {
                                            connection.query('INSERT IGNORE INTO video_item (name, videoId, sort, url) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [videoFile.split('.')[0], videoId, index + 1, path.join(folderPath, video.name, videoFile).split('E:')[1]], (error, results, fields) => {
                                                if (error) {
                                                    console.error(error);
                                                }
                                                else {
                                                    
                                                }
                                            });
                                        });
                                    }
                                });
                            })
                            
                        })
                    });
                    connection.release();
                });
                callback({code: 200});
            })
            .catch(err => {
                console.error(err);
            });
    }
    this.showVideos = function(id,callback){
        pool.getConnection(function(err,connection){
            connection.query('select * from video_item where id = ?',[id],function(err,data){
                if(err){
                    callback({code:500,msg:'服务器错误'}) 
                }else{
                    callback({code:200,msg:data[0].url})
                }
            })
           connection.release();
        })
    }
    this.getList = function(pageNum,pageSize,callback){
        redis.get(`video_list_num_${pageNum}_${pageSize}`,(err,res)=>{
            if(res){
                callback({ code: 200, msg: "查询成功!",rows:JSON.parse(res).rows ,total:JSON.parse(res).total});
            }else{
                pool.getConnection(function(err,connection){
                    if(typeof(callback)=='function'){
                        var query = `select * from video limit ${(pageNum-1)*pageSize},${pageSize}`
                        var query2=`SELECT COUNT(*) as total FROM video`
                        const P1=new Promise((resolve,reject)=>{
                            connection.query(query,function(err,data){
                                if(err){
                                    reject(err)
                                }else{
                                    resolve(data)
                                }
                            })
                        })
                        const P2=new Promise((resolve,reject)=>{
                            connection.query(query2,function(err,data){
                                if(err){
                                    reject(err)
                                }else{
                                    resolve(data) 
                                }
                            })
                        })
                        Promise.all([P1,P2]).then(result=>{
                            redis.set(`video_list_num_${pageNum}_${pageSize}`,JSON.stringify({rows:result[0],total:result[1][0].total}),'EX',600)
                            callback({ code: 200, msg: "查询成功!",rows:result[0] ,total:result[1][0].total});
                        },err=>{ 
                            console.log("err",err)
                        })
                    }
                })  
            }
        }) 
        
    }
    this.getVideoList = function(id,callback){
        redis.get(`video_num_${id}`,(err,res)=>{
            if(res){
                callback({ code: 200, msg: "查询成功!",rows:JSON.parse(res) });
            }else{
                pool.getConnection(function(err,connection){
                    if(typeof(callback)=='function'){
                        var query = `select * from video_item where videoId=?`
                        var inset = [id]
                        connection.query(query,inset,function(err,data){
                            if(err){
                                callback({ code: 500, msg: "查询失败!"});
                            }
                            else{
                                redis.set(`video_num_${id}`,JSON.stringify(data),'EX',600)
                                callback({ code: 200, msg: "查询成功!",rows:data});
                            }
                        })
                    }
                })
            }
        })
        
    }
    this.getVideoItem = function(id,callback){
        redis.get(`vide_item_${id}`,(err,res)=>{
            if(res){
                callback({ code: 200, msg: "查询成功!",data:JSON.parse(res) });
            }else{
                pool.getConnection(function(err,connection){
                    if(typeof(callback)=='function'){
                        var query = `select * from video_item where id=?`
                        var inset = [id]
                        connection.query(query,inset,function(err,data){
                            if(err){
                                callback({ code: 500, msg: "查询失败!"});
                            }
                            else{
                                redis.set(`vide_item_${id}`,JSON.stringify(data[0]),'EX',600)
                                callback({ code: 200, msg: "查询成功!",data:data[0]});
                            }
                        })
                    }
                })
            }
        })
        
    }
    this.getVideo = function(id,callback){
        redis.get(`video_${id}`,(err,res)=>{
            if(res){
                callback({ code: 200, msg: "查询成功!",data:JSON.parse(res) });
            }else{
                pool.getConnection(function(err,connection){
                    if(typeof(callback)=='function'){
                        var query = `select * from video where id=?`
                        var inset = [id]
                        connection.query(query,inset,function(err,data){
                            if(err){
                                callback({ code: 500, msg: "查询失败!"});
                           }
                           else{
                                redis.set(`video_${id}`,JSON.stringify(data[0]),'EX',600)
                                callback({ code: 200, msg: "查询成功!",data:data[0]});
                           }
                        })
                    }
                })
            }
        })
         
    }
    this.getVideos = function(path,callback){
        // 访问本地路径
        var p = 'E:/ruoyi/uploadPath'+ path.split('/profile')[1]
        fs.readFile(p, function(err, data) {
            if (err) {
                console.log(err);
                return;
            }
            callback(p);
        });
    }
}
module.exports = new Model()